package com.atguigu.day26.problem03;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
事务处理:
   开启事务: connection.setAutoCommit(false);
   提交:  connection.commit();
   回滚:  connection.rollback();
 */
public class TransactionTest {
    @Test
    public void test01(){

        //1.注册驱动
        //2.获取连接
        Connection connection = null;
        PreparedStatement pst=null;
        try {

            connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "1234");
            //todo 开启事务
            connection.setAutoCommit(false);
            //3.准备sql
            String sql = "update t_account set balance = balance+? where aname = ?";
            //4.创建命令发送器
            pst = connection.prepareStatement(sql);
            //5.李白-2000
            pst.setObject(1,2000);
            pst.setObject(2,"李白");
            pst.executeUpdate();

            //int m = 10/0;
            //6.杜甫+2000
            pst.setObject(1,-2000);
            pst.setObject(2,"杜甫");
            pst.executeUpdate();
            System.out.println("转账成功");
            //todo 没有问题 提交
            connection.commit();
        } catch (Exception e) {
            System.out.println("有内鬼 终止交易");
            try {
                //todo 有问题 回滚
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(pst!=null){
                try {
                    pst.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        //7.关闭资源


    }
}
